// ----------------------------------------
// Filename: UART.c
// Description: Routines to implement UART
// Author: Anton Jatmiko
// Date: 24-May-14

#include "UART.h"

// ----------------------------------------
// UART_Init
//
// Initialise UART and its peripheral
// Input:
//   none
// Output:
//   none
// Conditions:
//   none
void UART_Init(void)
{
    // EUSART pins' direction is automatically reconfigured
    TRISCbits.RC7 = 1;      // Rx pin
    TRISCbits.RC6 = 1;      // Tx pin

    SPBRG = 103;            // Baudrate = 9600, error = 0.16%
    BAUDCONbits.BRG16 = 1;  // 16-bit BRG
    TXSTAbits.BRGH = 1;     // High speed

    TXSTAbits.SYNC = 0;     // Asynchronous
    RCSTAbits.SPEN = 1;     // Enable serial ports

    PIE1bits.RCIE = 0;      // Disable Rx interrupt
    IPR1bits.RCIP = 1;      // Set Rx interrupt priority to high

    TXSTAbits.TX9 = 0;      // 8-bit transmission
    TXSTAbits.TXEN = 1;     // Enable transmit

    RCSTAbits.RX9 = 0;      // 8-bit reception
    RCSTAbits.CREN = 0;     // Disable receiver

    PIR1bits.TXIF = 0;
    IPR1bits.TXIP = 1;      // Set Tx interrupt priority to high
    PIE1bits.TXIE = 0;      // Enable Tx interrupt
}

// ----------------------------------------
// UART_WriteChar
//
// Write a byte to UART buffer
// Input:
//   data is the byte to be written
// Output:
//   none
// Conditions:
//   assume UART has been initialised
void UART_WriteChar(UINT8 data)
{
    while (!TXSTAbits.TRMT);
    TXREG = data;
}

// ----------------------------------------
// UART_WriteStr
//
// Write a string to UART buffer
// Input:
//   dataPtr is a pointer to the string
// Output:
//   none
// Conditions:
//   assume UART has been initialised
void UART_WriteStr(UINT8 * dataPtr)
{
    while (*dataPtr)
    {
        UART_WriteChar(*dataPtr);
        ++dataPtr;
    }
}